<template>
  <div>
    <Load :hideLoad="hideLoad"></Load>
    <div :class="{hide:hideDetails}">
        <el-input type="textarea"
                  rel="inputWidth"
                  v-model="description"
                  @change="onChangeDesc"
                  autosize>
        </el-input>
      <div class="height20"></div>
        <div class="tab-tit clear">
          <TabTit class="fl"
                  :item="item"
                  :index="index"
                  :selected="selected"
                  :deleteVisible="deleteVisible"
                  :repeatable="repeatable"
                  v-for="(item,index) in files"
                  :key="index"
                  @onchangeTab="onChangeTabHandle(index)">
          </TabTit>
          <span class="gistAdd fl">
            <i class="el-icon-circle-plus-outline" @click="addFile"></i>
          </span>
        </div>
        <File
          :item="item"
          :index="index"
          v-show="selected === index"
          :key="index"
          v-for="(item,index) in files">
        </File>
        <div class="btn" v-show="savable">
          <el-button type="primary"
                     size="medium"
                     :disabled="!savable"
                     @click="onUpdateItem">
            保存
          </el-button>
        </div>
      </div>
  </div>
</template>

<script>
  import http from "axios"
  import bus from './../../bus.js'
  import TabTit from '@/components/List/TabTit'
  import Load from '@/components/List/Load'
  import File from '@/components/List/File'

  export default {
    name: "Gist",
    components: {Load, TabTit, File},
    data() {
      return {
        id: this.$route.query.id,
        hideLoad: false,
        hideDetails:true,
        repeatable:false,
        activeName: "",
        selected: 0,
        newFileIndex: 0,
        description: "",
        files: [],
        fileCRUD: {}
      }
    },
    beforeRouteUpdate(to, from, next) {
      if (Object.keys(this.fileCRUD).length !== 0) {
        this.$confirm('检测到未保存的内容，是否在离开页面前保存修改？', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '保存',
          cancelButtonText: '放弃修改'
        })
          .then(() => {
            this.onUpdateItem();
            this.fileCRUD = {};
            this.id = to.query.id;
            this.getFiles(this.id);
            bus.$emit("addWidth");
            next();
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                ? '放弃保存并离开页面'
                : '停留在当前页面'
            })
            this.fileCRUD = {};
            this.hideLoad = false;
            this.id = to.query.id;
            this.getFiles(this.id);
            next();
          })
      } else {
        this.hideLoad = false;
        this.fileCRUD = {};
        this.id = to.query.id;
        this.getFiles(this.id);
        next();
      }
    },
    computed: {
      savable() {
        return this.fileCRUD.deletable
          || this.fileCRUD.editable
          || this.fileCRUD.addable
      },
      deleteVisible(){
        return this.files.filter(item => !item.deleted).length > 1
      }
    },
    mounted() {
      bus.$on("hideGistDetails",()=>{
        this.hideLoad= true;
        this.hideDetails= true;
      });
      bus.$on("showDetails",()=>{
        this.hideLoad = false;
        this.hideDetails= true;
      });
      this.getFiles(this.id);
      bus.$on("onNameChangedHandle", (obj) => {
        this.fileCRUD = obj;
      });
      bus.$on("onContentChanged", () => {
        this.$set(this.fileCRUD,"editable",true);
      })
//      点击删除文件
      bus.$on("onDeleteFiles",(index)=>{
        this.$set(this.fileCRUD,"deletable",true);
//        重新显示index
         var arrFiles=this.files;
         for(var i=0;i<arrFiles.length;i++){
           if(arrFiles[i].deleted === undefined){
             this.selected = i;
             break;
           }
         }
      });
      bus.$on("defaultSelected",()=>{
        this.selected = 0;
//        bus.$emit("defaultContent");
      });
      bus.$on("repeatFilename",name=>{
          if(this.files.filter(item=>item.filename === name).length>1){
              this.repeatable = true;
          }
      });
    },
    methods: {
      getFiles(id) {
        http.get("https://api.github.com/gists/" + id, {
          headers: {
            "Authorization": "token " + localStorage.getItem("token")
          }
        }).then((r) => {
          this.hideLoad = true;
          this.hideDetails = false;
          this.description = r.data.description;
          this.files = Object.values(r.data.files);
          this.files.forEach(item=>{
            item["oldname"] = item.filename;
          });
          this.activeName = this.files[0].filename;
        })
          .catch();
      },
      onChangeDesc() {
        this.$set(this.fileCRUD, "editable", true);
      },
      onChangeTabHandle(index) {
        this.selected = index;
        bus.$emit("changeContent", index);
      },
      addFile() {
        var filename = "file_" + this.newFileIndex++;
        this.files.push({
          filename: filename,
          content: "",
        });
        this.selected = this.files.length-1;
        bus.$emit("showEditContent");
      },
      onUpdateItem() {
        var data = {};
        data.description = this.description;
        if (this.description && this.description.length === 0) {
          alert("详情描述不能为空");
          return;
        }
        data.files = {};
        this.files.forEach((item) => {
          if (item.oldname !== undefined) {
//                更新文件
            if (item.editable) {
              data.files[item.oldname] = {
                filename: item.filename,
                content: item.content
              }
            }
//                删除文件
            if (item.deleted) {
              data.files[item.oldname] = null;
            }
          } else {
            //                    添加文件
            data.files[item.filename] = {
              content: item.content
            }
          }
        })
        console.log(data);
        http.patch("https://api.github.com/gists/" + this.id, data, {
          headers: {
            "Authorization": "token " + localStorage.getItem("token")
          }
        }).then((r) => {
          console.log(r);
          this.files = Object.values(r.data.files);
          this.files.forEach(item=>{
            item["oldname"] = item.filename;
          });
          this.open();
          bus.$emit("updateList", {
            id: this.id,
            files: this.files,
            description: this.description
          });
          bus.$emit("changeEditContent");
          this.fileCRUD = {};
          this.selected=0;
        })
          .catch();
      },
      open() {
        this.$message({
          message: '恭喜你，保存成功',
          type: 'success'
        });
      }
    }
  }
</script>

<style scoped>
  .btn {
    margin-top: 20px;
  }
  .gistAdd{
    top: 5px;
    font-weight: normal;
    float: right;
  }
</style>
